package cn.thoughtworks.school.programCenter.controllers;

import cn.thoughtworks.school.programCenter.annotations.Auth;
import cn.thoughtworks.school.programCenter.entities.TaskContentRead;
import cn.thoughtworks.school.programCenter.entities.User;
import cn.thoughtworks.school.programCenter.exceptions.BusinessException;
import cn.thoughtworks.school.programCenter.repositories.TaskContentReadRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping(value = "/api/tasks")
public class TaskContentReadController {
    @Autowired
    private TaskContentReadRepository taskContentReadRepository;

    @RequestMapping(value = "/{taskId}/contentRead", method = RequestMethod.POST)
    public ResponseEntity addTasksContentRead(@PathVariable Long taskId, @Auth User current) throws BusinessException {
        if (taskContentReadRepository.findByTaskIdAndStudentId(taskId, current.getId()).isEmpty()) {
            TaskContentRead taskContentRead = new TaskContentRead();
            taskContentRead.setStudentId(current.getId());
            taskContentRead.setTaskId(taskId);
            taskContentRead.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(new Date()));
            taskContentReadRepository.save(taskContentRead);
            return new ResponseEntity<>(HttpStatus.CREATED);
        }
        throw new BusinessException("请勿重复点击");
    }

    @RequestMapping(value = "/{taskId}/contentRead", method = RequestMethod.GET)
    public ResponseEntity getTasksContentReadByTaskId(@PathVariable Long taskId, @Auth User current) {

        List<TaskContentRead> taskContentReads = taskContentReadRepository
            .findByTaskIdAndStudentId(taskId, current.getId());
        if (taskContentReads.isEmpty()) {
            return new ResponseEntity<>(new TaskContentRead(), HttpStatus.OK);
        }
        return new ResponseEntity<>(taskContentReads.get(0), HttpStatus.OK);
    }

}
